package com.stx.openeyes.view.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaeger.library.StatusBarUtil;
import com.stx.openeyes.R;
import com.stx.openeyes.SealConst;
import com.stx.openeyes.adapter.MyAdapter;
import com.stx.openeyes.adapter.MyVideoItemAdapter;
import com.stx.openeyes.dto.Response;
import com.stx.openeyes.model.HomePicEntity;
import com.stx.openeyes.model.User;
import com.stx.openeyes.model.Video;
import com.stx.openeyes.utils.ContextUtil;
import com.stx.openeyes.utils.HttpAdress;
import com.stx.openeyes.utils.NToast;
import com.stx.openeyes.widget.LoadDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import okhttp3.Call;

public class MyVideoListActivity extends AppCompatActivity {

    private static final String TAG = "MyVideoListActivity";
    protected Context mContext;
    private Gson mGson;
    @BindView(R.id.video_item_listview)
    ListView lvHome;
    @BindView(R.id.main_toolbar_iv_right)
    ImageButton mainToolbarIvRight;

    Intent getIntent;

    private MyVideoItemAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_video_list_view);
        StatusBarUtil.setTranslucent(this);
        ButterKnife.bind(this);
        mContext = this;
        getIntent = getIntent();
        initEvent();
        setToolBar();
        setLvAdapter();

        downLoad(HttpAdress.USER_VIDEO);

        setListener();
    }

    private void initEvent() {
        int type = getIntent.getIntExtra("type", 0);
        if (1 == type) {
            mainToolbarIvRight.setVisibility(View.VISIBLE);
            mainToolbarIvRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OkHttpUtils.delete()
                        .url(HttpAdress.VIDEO_HISTORY_DEL)
                        .addHeader("token", ContextUtil.getCurrentUserToken())
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                Log.i("===error",e.getMessage());
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                Log.i("===json",response);
                                listAll.clear();
                                myNotify();
                            }
                        });
                }
            });
        }
    }

    List<Video> listAll = new ArrayList<Video>();

    private void downLoad(final String url) {
        if (TextUtils.isEmpty(url)){
            return;
        }
        mGson = new Gson();
        int type = getIntent.getIntExtra("type", 0);
        if (type == 4) {
            SharedPreferences settings = getSharedPreferences(SealConst.DOWNLOAN_VIDEOS, 0);
            String infos = settings.getString(SealConst.DOWNLOAN_VIDEO_INFO, null);

            if (infos == null)
                return;

            List<Video> videoList  = mGson.fromJson(infos, new TypeToken<List<Video>>() {
            }.getType());
            if (videoList != null) {
                listAll.addAll(videoList);
                myNotify();
                autoFlash();
            }
        } else {
            OkHttpUtils.get()
                .url(String.format(url, type))
                .addHeader("token", ContextUtil.getCurrentUserToken())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("===error", e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("===json", response);
                        Response<List<Video>> videoResponse = mGson.fromJson(response, new TypeToken<Response<List<Video>>>() {
                        }.getType());
                        listAll.addAll(videoResponse.getData());
                        myNotify();
                    }
                });
        }
    }


    public void myNotify() {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void autoFlash() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SharedPreferences settings = getSharedPreferences(SealConst.DOWNLOAN_VIDEOS, 0);
                            String infos = settings.getString(SealConst.DOWNLOAN_VIDEO_INFO, null);

                            if (infos == null)
                                return;

                            List<Video> videoList  = mGson.fromJson(infos, new TypeToken<List<Video>>() {
                            }.getType());
                            if (videoList != null) {
                                listAll.clear();
                                listAll.addAll(videoList);
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    });
                }
            }
        });
        thread.start();
    }

    private void setLvAdapter() {
        mAdapter = new MyVideoItemAdapter(mContext, listAll);
        lvHome.setAdapter(mAdapter);
    }

    private void setToolBar() {
        Toolbar tb = (Toolbar) findViewById(R.id.tb_my_recommend);
        setSupportActionBar(tb);
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayShowTitleEnabled(false);
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        tb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        TextView titleTv = (TextView) findViewById(R.id.vide_item_tv_title);
        String title = getIntent.getStringExtra("title");
        titleTv.setText(title);
    }

    private void setListener() {
        lvHome.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, VideoDetailActivity.class);
                Bundle bundle = new Bundle();
                Video data = listAll.get(position);
                bundle.putInt("id", data.getId()); // 视频id
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        listAll.clear();
        downLoad(HttpAdress.USER_VIDEO);
    }
}
